package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	jsoniter "github.com/json-iterator/go"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"newRetailByGolang/model"
	"newRetailByGolang/variable"
	"time"
)

type OrderConsumer struct {

}

func NewOrderConsumer() *OrderConsumer{
	return new(OrderConsumer)
}

func NewDb() *gorm.DB{
	dsn := "root:new_password@tcp(127.0.0.1:3306)/new_retail_by_golang?charset=utf8mb4&parseTime=True&loc=Local"
	Db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil{
		panic("db error")
	}

	sqlDb, pErr := Db.DB()
	if pErr != nil{
		panic("db error")
	}
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)

	return Db
}

func NewRedisInit() *redis.Conn{
	pool := &redis.Pool{
		MaxIdle : 10,
		MaxActive : 0,
		IdleTimeout : 100,
		Dial : func()(redis.Conn, error){
			return redis.Dial("tcp", "127.0.0.1:6379")
		},
	}
	poolConn := pool.Get()

	return &poolConn
}

func (oc *OrderConsumer)ConsumerOrder() {
	poolConn := NewRedisInit()
	Db := NewDb()
	for {
		ele, err := (*poolConn).Do("lpop", variable.RMQ)
		if err != nil {
			fmt.Println("no msg.sleep now：", err)
		} else {
			if ele != nil {
				var o model.Order
				jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(ele.([]byte), &o)
				fmt.Println(o.GoodId)
				fmt.Println(o.GoodName)
				fmt.Println("-------------------------------------------------------------------------------")

				o.CreatedAt = time.Now()
				o.UpdatedAt = time.Now()
				Db.Create(&o)

				Db.Model(&o).Update("user_name", "redis queue 更新木有。。。。")

				Db.Delete(&model.Order{}, 15)
			}
		}
	}
}

func main()  {
	NewOrderConsumer().ConsumerOrder()
}
